/**
 ----------------------
 1.整张表的增删改查
 2.逻辑复用
 ----------------------
 */
import {useUploadFile} from '@/utils/file/file';
import {noticeFormConfig} from './form';
import {noticeTable} from './table';
import {
    deleteNotice,
    fetchNoticeById,
    fetchNoticeList,
    exportNotice,
    importNotice,
} from '@/api/modules/system/notice/notice';
import {response} from '@/utils/table/table';
import {setContextMenu} from '@/views/components/contextmenu/data';
import type {SystemNotice} from '@/api/modules/system/notice/types';
/**
 * @description: 根据条件获取列表数据
 */
export const noticeList = async () => {
    try {
            noticeTable.value.loading = true;
        const {data} = await fetchNoticeList(noticeTable.value.query);
            noticeTable.value.data = data.rows;
            noticeTable.value.query.total = data.total;
            noticeTable.value.loading = false;
    } catch (error) {
            noticeTable.value.loading = false;
    }
};

/**
 * @description: 根据ID查询数据,并打开表单页面
 * @param {number} id
 */
export const noticeEdit = async (id?: number) => {
    let targetId: number | string = id ? id : noticeTable.value.keys[0];
        noticeTable.value.loading = true;
    const {data} = await fetchNoticeById(targetId);
    if (data.data) {
            noticeFormConfig.value.form = data.data;
            noticeFormConfig.value.display = true;
    }
        noticeTable.value.loading = false;
};

/**
 * @description:
 * 清空表单所有内容
 * 打开表单页面
 */
export const noticeCreate = async () => {
        noticeFormConfig.value.display = true;
        noticeFormConfig.value.reset!();
};

export const noticeDelete = async (id?: number) => {
    let ids = id ? [id] : noticeTable.value.keys;
    await response(deleteNotice, ids);
    await noticeList();
        noticeTable.value.keys = [];
};

// 导出EXCEL文件
export const noticeExport = () => {
    return exportNotice(noticeTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const noticeSearch = () => {
        noticeTable.value.query.pageNum = 1;
        noticeList();
};

/**
 * @description: 使用excel导入文件
 */
export const noticeImport = async () => {
    const files = await useUploadFile({
        accept: '.xls, .xlsx',
    });
    importNotice(files[0]);
};

/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {SystemNotice} item
 */
export const displayNoticeMenu = (item: SystemNotice) => {
        noticeFormConfig.value.form = item;
        noticeTable.value.keys = [item.noticeId];
    setContextMenu({
        items: noticeTable.value.contextmenu,
    });
};
